import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

// 默认菜单配置
const defaultMenuList = [
  { path: '/dashboard/user', title: '用户管理', icon: 'el-icon-user' },
  { path: '/dashboard/role', title: '角色管理', icon: 'el-icon-s-custom' },
  { path: '/dashboard/command', title: '命令管理', icon: 'el-icon-s-order' }
]

export default new Vuex.Store({
  state: {
    token: localStorage.getItem('token') || '',
    userInfo: JSON.parse(localStorage.getItem('userInfo') || '{}'),
    menuList: JSON.parse(localStorage.getItem('menuList') || JSON.stringify(defaultMenuList))
  },
  mutations: {
    SET_TOKEN(state, token) {
      state.token = token
      localStorage.setItem('token', token)
    },
    SET_USER_INFO(state, userInfo) {
      state.userInfo = userInfo
      localStorage.setItem('userInfo', JSON.stringify(userInfo))
    },
    SET_MENU_LIST(state, menuList) {
      state.menuList = menuList
      localStorage.setItem('menuList', JSON.stringify(menuList))
    },
    CLEAR_USER_DATA(state) {
      state.token = ''
      state.userInfo = {}
      state.menuList = defaultMenuList
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
      localStorage.removeItem('menuList')
    },
    INITIALIZE_MENU(state) {
      // 如果菜单数据为空，使用默认菜单
      if (state.menuList.length === 0) {
        state.menuList = defaultMenuList
        localStorage.setItem('menuList', JSON.stringify(defaultMenuList))
      }
    }
  },
  actions: {
    login({ commit }, { token, userInfo }) {
      commit('SET_TOKEN', token)
      commit('SET_USER_INFO', userInfo)
      
      // 根据用户权限设置菜单（这里简单处理，实际项目中应该根据用户角色返回不同菜单）
      let menuList = defaultMenuList
      
      // 如果是管理员，显示所有菜单
      if (userInfo.role === 'admin') {
        menuList = [...defaultMenuList]
      }
      // 如果是普通用户，只显示部分菜单
      else if (userInfo.role === 'user') {
        menuList = defaultMenuList.filter(menu => 
          menu.path !== '/dashboard/user' && menu.path !== '/dashboard/role'
        )
      }
      
      commit('SET_MENU_LIST', menuList)
    },
    logout({ commit }) {
      commit('CLEAR_USER_DATA')
    },
    initializeMenu({ commit }) {
      commit('INITIALIZE_MENU')
    }
  },
  getters: {
    isAuthenticated: state => !!state.token,
    userInfo: state => state.userInfo,
    menuList: state => state.menuList
  }
})